package com.suncreate.atm.utils;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import cn.hutool.setting.Setting;
import com.alibaba.druid.pool.DruidDataSource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.LinkedHashSet;

public class DataBasesUtils {

    // 加载配置文件
    static Setting setting = new Setting("jdbc.properties");

    static String vip = setting.get("VIP");

    /**
     * 创建数据源
     */
    public static DruidDataSource createDataSource(String url, String username, String password) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }



    /**
     * 判断是否是主键冲突异常
     */
    public static boolean isDuplicateEntryException(SQLException e) {
        // MySQL 主键冲突错误码为 1062
        return e.getErrorCode() == 1062 || e.getMessage().contains("Duplicate entry");
    }

    /**
     关闭数据库连接
    */
    public static void closeTheConnection(DruidDataSource dataSource){
        if (dataSource != null && !dataSource.isClosed()) {
            try {
                dataSource.close();
                StaticLog.info("数据连接已经关闭: "+ dataSource.createConnectionId());
            } catch (Exception e) {
                StaticLog.error(e);
            }
        }
    }

    public static boolean checkVIPPassed(){
        // 获取本机所有 IPv4 地址
        LinkedHashSet<String> localIPs = NetUtil.localIpv4s();

        // 判断是否包含目标 IP 地址
        if (localIPs.contains(vip)) {
            StaticLog.debug(StrUtil.format("本机包含目标 VIP 地址：{}，无须同步，提前结束程序 ", vip));
            return false;
        } else {
            StaticLog.info(StrUtil.format("本机不包含目标 VIP 地址：{}，继续执行同步程序", vip));
            return true;
        }
    }

    //判断当前进程是否正在运行
    public static boolean isProcessRunning(String processName) {
        int processCount=0;

        try {
            ProcessBuilder pb = new ProcessBuilder("pgrep", "-f", processName);
            Process process = pb.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            while (reader.readLine() != null) {
                StaticLog.info("Linux进程号："+reader.readLine());
                processCount++;
            }
        } catch (IOException e) {
            System.err.println("执行进程检查时发生异常：" + e.getMessage());
        }

        StaticLog.info(StrUtil.format("当前有{}个sc_mysql_sync正在执行中...", processCount));

        if(processCount > 2){
            StaticLog.info(StrUtil.format("有历史积压同步程序还在运行，提前结束本程序"));
            return true;
        }
        else{
            StaticLog.info(StrUtil.format("没有历史积压程序，本程序继续运行"));
            return false;
        }

    }

}